
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart'; //数据持久化

class CartPage extends StatefulWidget {
  CartPage({Key key}) : super(key: key);

  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage> {
  List<String> testList = [];
  @override
  Widget build(BuildContext context) {
    _show();
    return Scaffold(
      appBar: AppBar(title: Text('购物车'),centerTitle: true,),
      body:  Container(
        child: Column(
          children: <Widget>[
            Container(
              height: 500.0,
              child: ListView.builder(
                itemCount: testList.length,
                itemBuilder: (context,index){
                  return ListTile(
                    title:Text(testList[index]) ,
                  );
                },
              ),
            ),
            RaisedButton(
              onPressed:(){
                _add();
              },
              child:Icon(Icons.add) ,
            ),
            RaisedButton(
              onPressed:(){
                _clear();
              },
              child:Icon(Icons.clear) ,
            )
          ],
        ),
      ) ,
    );
  }
  //增加方法
  void _add() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String temp = "技术胖";
    testList.add(temp);
    print(prefs);
    await prefs.setStringList('testInfo', testList);
    _show();
  }
  //查询
  void _show() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getStringList('testInfo')!=null){
      setState(() {
       testList =  prefs.getStringList('testInfo');
      });
    }
  }
  //删去
  void _clear() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //prefs.clear() 全删
    prefs.remove('testInfo');
    setState(() {
       testList  = [];
    });
  }
}
